﻿using System;
using System.Threading;
using System.Threading.Tasks;
using MassTransit;
using MassTransitDemo.Shared;
using Microsoft.Extensions.Hosting;

namespace MassTransitDemo.ResponseService
{
    public class ResponseHostedService : IHostedService
    {
        IBusControl _busControl;

        public async Task StartAsync(CancellationToken stoppingToken)
        {
            var rabbitMQAddress = "119.3.138.127";
            var serviceQueueName = "masstransitdemo-events-listener";

            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                x.Host(rabbitMQAddress, 5672, "masstransitdemo", h =>
                {
                    h.Username("masstransitdemo");
                    h.Password("masstransitdemo@test");
                });

                x.ReceiveEndpoint(serviceQueueName, e =>
                {
                    e.Handler<ISimpleRequest>(context =>
                    {
                        Console.WriteLine($"Request:{context.Message.CustomerId}");
                        return context.RespondAsync(new SimpleResponse
                        {
                            CusomerName = string.Format("Customer Number {0}", context.Message.CustomerId)
                        });
                    });
                });
            });

            await _busControl.StartAsync();
        }

        public Task StopAsync(CancellationToken stoppingToken)
        {
            _busControl?.Stop();
            return Task.CompletedTask;
        }
    }
}
